package com.onpositive.realmview.basic;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import com.onpositive.realmview.AbstractRealmView;
import com.onpositive.realmview.IRealmView;
import com.onpositive.realmview.NamedObject;
import com.onpositive.realmview.model.ICommitableWorkingCopy;
import com.onpositive.realmview.model.IHasViews;
import com.onpositive.realmview.model.IWorkingCopy;
import com.onpositive.realmview.progress.IProgressMonitor;
import com.onpositive.semantic.model.api.property.IPropertyProvider;
import com.onpositive.semantic.model.api.property.java.JavaPropertyProvider;
import com.onpositive.semantic.model.realm.IModifiableRealm;

public class BasicRealmView extends AbstractRealmView {
	
	protected IPropertyProvider propertyProvider = new JavaPropertyProvider();

	public BasicRealmView(IHasViews<?> parent) {
		super(parent);
	}

	public BasicRealmView(IModifiableRealm<? extends NamedObject> parent,
			IHasViews<?> hv) {
		super(parent, hv);
	}

	@Override
	public IWorkingCopy copy(Object element) {
		return new BasicWorkingCopy(element,propertyProvider);
	}

	@Override
	protected HashMap<Object, IWorkingCopy> cloneCopies(IRealmView v) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected AbstractRealmView createCopy() {
		return new BasicRealmView(parent,owner);
	}

	@Override
	protected void readCopies(DataInputStream stream) {
		int count;
		try {
			count = stream.readInt();
			for (int i = 0; i < count; i++) {
				BasicWorkingCopy copy = new BasicWorkingCopy(null, new JavaPropertyProvider());
				copy.read(stream);
				if (copy.getOriginal() != null)
					copies.put(copy.getOriginal(), copy);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void storeCopies(DataOutputStream outputStream)
			throws IOException {
		outputStream.writeInt(copies.size());
		for (IWorkingCopy copy: copies.values()) {
			((BasicWorkingCopy) copy).store(outputStream);
		}
	}

	@Override
	public void commit(IProgressMonitor monitor, boolean locally) {
		if (!locally) {
			Set<Object> keySet = copies.keySet();
			for (Object object : keySet) {
				IWorkingCopy copy = copies.get(object);
				if (copy instanceof ICommitableWorkingCopy && ((ICommitableWorkingCopy) copy).commit())
					copies.remove(object);
			}
		}

	}

}
